/** 
  成绩变更审核（校管理员+院教务员）
*/
<template>
  <div class="score-change-apply-container">
    <!-- 成绩变更申请列表页开始 -->
    <div v-if="indexKey === 0">
      <condition-card @reset="reset" @search="onSubmit" label-position="right" label-width="150px">
        <el-row :gutter="24" style="height: 50px;">
          <!-- 学年学期 -->
          <el-col :span="8">
            <el-form-item :label="$t('scoreEntrySwitch.semester')">
              <calendar-select ref="semester" v-model="queryForm.condition.calendarId" @load-done="calendarIdLoadDone" :placeholder="$t('common.pla.pleaseSelect')"></calendar-select>
            </el-form-item>
          </el-col>
          <!-- 课程代码/名称 -->
          <el-col :span="8">
            <el-form-item :label="$t('courseScoreMana.teachingClassCode')">
              <el-select
                v-model.trim="queryForm.condition.courseCodeOrName"
                :remote-method="remoteMethod"
                filterable
                remote
                clearable
                :placeholder="$t('common.pla.pleaseInput')"
                style="width:100%">
                <el-option
                  v-for="item in options.courseCodeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 课程序号 -->
          <el-col :span="8">
            <el-form-item :label="$t('scoreEntryMana.courseNum')">
              <el-input :placeholder="$t('common.pla.pleaseInput')" v-model="queryForm.condition.courseNum" :maxlength="32" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="height: 50px;">
          <!-- 课程类别 -->
          <!-- <el-col :span="8">
            <el-form-item :label="$t('scoreEntryMana.courseType')">
              <el-select v-model="queryForm.condition.courseLabel" clearable style="width: 100%">
                  <el-option
                    v-for="item in options.courseType"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <!-- 审核状态 -->
          <el-col :span="8">
            <el-form-item :label="$t('scoreMangementBase.auditStatus')">
              <el-select v-model="queryForm.condition.auditStatus" clearable style="width: 100%">
                  <el-option
                    v-for="item in options.auditStatusOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </condition-card>
      <el-card
        v-loading="loading"
        shadow="never"
        body-style="padding: 24px;"
        style="margin-top:24px">
        <h1 class="condition-title">{{ $t('scoreChangeApply.studentList') }}</h1>
        <div class="div-main clearfix">
          <div class="float-left">
            <el-input
              clearable
              v-model="queryForm.condition.studentIdOrName"
              :placeholder="$t('scoreChangeApply.studentSearchText')"
              style="width:250px"
              @change="onSubmit"
              @keyup.enter.native="onSubmit">
                <i slot="prefix"
                  class="el-icon-search"
                  style="margin-top:10px;cursor:pointer"
                  @click="onSubmit">
                </i>
            </el-input>
          </div>
          <!-- 指定审核人 -->
          <!-- <div class="float-right">
            <el-button v-if="permitToPointAudit" @click="designateReviewer()">{{ $t('scoreChangeAudit.designatedReviewer') }}</el-button>
          </div> -->
        </div>
        <edu-table :pagination="false" :order='true' :tooltipEffect="tooltipEffect" stripe :data="dataList" size="mini" @selection-change="handleSelectionChange">
          <!-- 学号 -->
          <edu-table-column :label="$t('scoreMangementBase.studentId')" prop="studentId"></edu-table-column>
          <!-- 姓名 -->
          <edu-table-column :label="$t('scoreMangementBase.studentName')" prop="studentName"></edu-table-column>
          <!-- 课程代码 -->
          <edu-table-column :label="$t('scoreEntryMana.courseCode')" prop="courseCode"></edu-table-column>
          <!-- 课程名称 -->
          <edu-table-column :label="$t('scoreEntryMana.courseName')" prop="courseName"></edu-table-column>
          <!-- 课程序号 -->
          <edu-table-column :label="$t('scoreEntryMana.courseNum')" prop="courseNum"></edu-table-column>
          <!-- 课程类别 -->
          <edu-table-column :label="$t('scoreEntryMana.courseType')" prop="courseLabel"></edu-table-column>
          <!-- 成绩 -->
          <edu-table-column :label="$t('scoreMangementBase.grade')" prop="scoreValue"></edu-table-column>
          <!-- 学分 -->
          <edu-table-column :label="$t('scoreEntryMana.credit')" prop="credit"></edu-table-column>
          <!-- 绩点 -->
          <edu-table-column :label="$t('gradeRelatedSetting.gradePoint')" prop="gradePoint"></edu-table-column>
          <!-- 审核状态 -->
          <edu-table-column :label="$t('scoreEntryMana.status')" prop="auditStatus">
            <template slot-scope="scope">
              <!-- 审核中 -->
              <el-tag
                v-if="scope.row.auditStatus === '1'"
                >{{ $t('scoreChangeApply.approvalling') }}
              </el-tag>
              <!-- 审核通过 -->
              <el-tag
                v-if="scope.row.auditStatus === '2'"
                type="success">{{ $t('scoreChangeApply.appPass') }}
              </el-tag>
              <!-- 驳回 -->
              <el-tag
                v-if="scope.row.auditStatus === '3'"
                type="warning">{{ $t('scoreMangementBase.reject') }}
              </el-tag>
            </template>
          </edu-table-column>
          <!-- 操作 -->
          <edu-table-column :label="$t('common.text.operation')" prop="operation" fit>
            <template slot-scope="scope">
              <!-- 查看 -->
              <el-button v-if="permitToSelect" type="text" @click="selectInfo(scope.row)">{{ $t('scoreMangementBase.select') }}</el-button>
              <!-- 审核 -->
              <el-button v-if="permitToAudt && scope.row.canAudit" type="text" @click="auditInfo(scope.row)">{{ $t('scoreMangementBase.audit') }}</el-button>
            </template>
          </edu-table-column>
        </edu-table>
        <el-row type="flex" class="row-bg" justify="end">
          <el-col>
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="queryForm.pageNum_"
              :page-sizes="[20, 40, 80, 100]"
              :page-size="queryForm.pageSize_"
              layout="total, sizes, prev, pager, next, jumper"
              :total="queryForm.total_"
              style="float:right;margin-top:10px"
            ></el-pagination>
          </el-col>
        </el-row>
      </el-card>
    </div>
    <!-- 成绩变更申请列表页结束 -->
    <!-- 审核开始 -->
    <div v-if="indexKey === 1">
      <audit-score-change :detailInfo="detailInfo" :permitToLevelOneAudit="permitToLevelOneAudit" @refresh-main-page="backToMain"></audit-score-change>
    </div>
    <!-- 审核结束 -->
    <!-- 查看开始 -->
    <div v-if="indexKey === 2">
      <apply-score-change-select :detailInfo="detailInfo" :breadcrumbInfo="breadcrumbInfo" @refresh-main-page="backToMain"></apply-score-change-select>
    </div>
    <!-- 查看结束 -->
    <!-- 指定审核人开始 -->
    <el-dialog
      ref="teacherDialog"
      :before-close="beforeClose"
      :title="title"
      width="30%"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-form :model="dialogForm" label-position="right" ref="dialogForm" label-width="90px" style="padding-right: 30px;">
        <el-row>
          <el-col :span="24">
            <!-- 教师 -->
            <el-form-item
              :label="$t('scoreEntryMana.tearcher') + '：'"
              prop="selectTeacherName"
              :rules="[{ required: true, message: $t('scoreEntryMana.requireTeacher'), trigger: 'blur' }]">
              <el-select
                v-model="dialogForm.selectTeacherName"
                :placeholder="$t('score.pleaseInputKey')"
                :remote-method="teacherRemoteMethod"
                filterable
                remote
                style="width: 100%;">
                <el-option
                  v-for="item in options.teacherList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                  <span style="float: left">{{ item.label }}{{ "(" + item.value + ")" }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.facultyI18n }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <template>
          <el-button @click="cancel('dialogForm')">{{ $t('common.btn.cancel') }}</el-button>
          <el-button type="primary" @click="confirm('dialogForm')">{{ $t('common.btn.confirm') }}</el-button>
        </template>
      </span>
    </el-dialog>
    <!-- 指定审核人结束 -->
    <!-- 指定审核人二次确认弹框开始 -->
    <el-dialog
      :visible.sync="settingEnterPerson"
      :before-close="handleClose"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="$t('scoreMangementBase.prompt')"
      width="400px">
      <span>{{ $t('courseScoreMana.confirmDesignatedEntry') }}</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="settingEnterPerson = false">{{ $t('common.btn.cancel') }}</el-button>
        <el-button type="primary" @click="confirmSettingEnterPerson">{{ $t('common.btn.confirm') }}</el-button>
      </span>
    </el-dialog>
    <!-- 指定审核人二次确认弹框结束 -->
  </div>
</template>
<script>
import scoreManagementApi from 'common/src/api/scoreManagement/scoreManagement';
import { queryDic } from 'common/src/api/dictionary';
import { findTeacherList } from 'common/src/api/resource/teachers';
import { coursesLabelList } from 'common/src/api/score/courseScoreChangeMange.js';
import auditScoreChange from './auditScoreChange';
import applyScoreChangeSelect from '../common/applyScoreChangeSelect';
export default {
  components: {
    'audit-score-change': auditScoreChange,
    'apply-score-change-select': applyScoreChangeSelect
  },
  data () {
    return {
      initMode: true,
      auths: [],
      userInfo: {},
      permitToPointAudit: false,
      permitToLevelOneAudit: false,
      permitToSelect: false,
      permitToAudt: false,
      indexKey: 0,
      breadcrumbInfo: {
        path: '',
        parentTitle: ''
      },
      dataList: [],
      multipleSelection: [],
      queryForm: {
        condition: {
          calendarId: '',
          courseCodeOrName: '',
          courseNum: '',
          courseLabel: '',
          auditStatus: '',
          studentIdOrName: ''
        },
        pageNum_: 1,
        pageSize_: 20,
        total_: 0
      },
      options: {
        courseCodeList: [],
        courseType: [],
        auditStatusOption: [
          {
            value: '1',
            label: '审核中'
          },
          {
            value: '2',
            label: '审核通过'
          },
          {
            value: '3',
            label: '驳回'
          }
        ],
        teacherList: []
      },
      title: '',
      dialogVisible: false,
      dialogForm: {
        selectTeacherName: ''
      },
      settingEnterPerson: false,
      detailInfo: {},
      operateMode: ''
    }
    
  },
  props: {

  },
  filters: {
    auditStatus(val) {
      switch(val) {
        case '1':
          return '审核中'
        case '2':
          return '审核通过'
        case '3':
          return '驳回'
        default:
          return val
      }
    }
  },
  created() {
    // 获取当前用户auths权限
    if (localStorage.getItem("sessiondata")) {
      if (JSON.parse(localStorage.getItem("sessiondata")).auths) {
        this.auths = JSON.parse(localStorage.getItem("sessiondata")).auths
      }
      if (JSON.parse(localStorage.getItem("sessiondata")).mockUser) {
        this.userInfo = JSON.parse(localStorage.getItem("sessiondata")).mockUser
      } else {
        this.userInfo = JSON.parse(localStorage.getItem("sessiondata")).user
      }
    }
  },
  mounted() {
    if (this.queryForm.condition.calendarId) {
      this.onSubmit()
    }
    this.getCourseType()
    this.initMode = true
  },
  methods: {
    // 校验特殊字符$
    checkSpecial(rule, value, callback) {
      let regEn = /[`$]/im
      if (regEn.test(value)) {
        callback(new Error(this.$t('graduateBase.specialText')))
      } else {
        callback()
      }
    },
    calendarIdLoadDone() {
      if (this.initMode) {
        this.onSubmit()
      }
    },
    onSubmit() {
      this.queryForm.pageNum_ = 1
      this.getListData()
    },
    getListData() {
      scoreManagementApi.getScoreChangeAuditList(this.queryForm).then((res) => {
        this.dataList = res.data.list
        this.queryForm.total_ = res.data.total
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSizeChange(val) {
      this.queryForm.pageSize_ = val
      this.getListData()
    },
    handleCurrentChange(val) {
      this.queryForm.pageNum_ = val
      this.getListData()
    },
    reset() {
      for (let key in this.queryForm.condition) {
        if (key !== 'calendarId') {
          this.queryForm.condition[key] = ''
        }
      }
      this.queryForm.condition.calendarId = this.$refs.semester.$data.currentTermId
      this.onSubmit()
    },
    // 返回主页
    backToMain() {
      this.initMode = false
      this.multipleSelection = []
      this.indexKey = 0
      this.operateMode = ''
      this.onSubmit()
    },
    // 课程代码、名称搜索方法
    remoteMethod(val) {
      if (val !== '') {
        this.loading = true
        let lang = this.$store.getters.language
        scoreManagementApi.queryCourseInfoByCourseCode({
          courseCode: val
        }).then(res => {
          this.loading = false
          if (res.code == 200) {
            const list = res.data &&
              res.data.map(e => {
                let obj = {}
                obj.label = lang === 'cn' ? e.name + '(' + e.code + ')' : e.nameEn + '(' + e.code + ')'
                obj.value = e.code
                return obj
              })
            this.options.courseCodeList = list
          }
        })
      } else {
        this.options.courseCodeList = []
        this.queryForm.condition.courseCodeOrName = ''
      }
    },
    // 获取课程类别
    getCourseType() {
      let val = ''
      coursesLabelList(val).then(res => {
        res.data.forEach(item => {
          this.options.courseType.push({
            label: item.label,
            value: item.id,
            key: item.id
          })
        })
      })
    },
    // 查看
    selectInfo(row) {
      this.breadcrumbInfo.path = '/scoreChangeAudit'
      this.breadcrumbInfo.parentTitle = this.$t('scoreChangeAudit.scoreChangeAudit')
      this.detailInfo = {
        id: row.id,
        studentId: row.studentId,
        calendarId: row.calendarId,
        auditStatus: row.auditStatus
      }
      this.indexKey = 2
    },
    // 审核
    auditInfo(row) {
      this.operateMode = ''
      this.detailInfo = {
        id: row.id,
        studentId: row.studentId,
        calendarId: row.calendarId,
        auditStatus: row.auditStatus
      }
      this.indexKey = 1
      // 判断该记录是否指定审核
      // 已指定（包含指定和不指定）
      // if (row.isAppoint) {
      //   this.indexKey = 1
      // } else {
      //   this.$confirm(this.$t('scoreChangeAudit.isDesignatedReviewer'), this.$t('scoreMangementBase.prompt'), {
      //     confirmButtonText: this.$t('scoreMangementBase.confirm'),
      //     cancelButtonText: this.$t('scoreMangementBase.cancel'),
      //     type: 'warning'
      //   }).then(() => {
      //     this.title = this.$t('scoreChangeAudit.designatedReviewer')
      //     this.operateMode = 'audit'
      //     this.dialogVisible = true
      //   }).catch(e => {
      //     this.indexKey = 1
      //   })
      // }
    },
    // 指定审核人
    designateReviewer() {
      // 不勾选场景
      if (this.multipleSelection.length === 0) {
        this.$message.warning(this.$t('scoreMangementBase.pleaseChooseOne'))
        return
      }
      // 判定勾选数据中是否已包含已审核的
      let cannotAudit = false
      this.multipleSelection.map(value => {
        if (!value.canAudit) {
          cannotAudit = true
        }
      })
      if (cannotAudit) {
        this.$message.warning(this.$t('scoreChangeAudit.notCanDesignated'))
        return
      }
      // 若勾选的数据已经有指定审核人，二次弹框确认
      this.title = this.$t('scoreChangeAudit.designatedReviewer')
      this.dialogVisible = true
    },
    // 关闭前回调
    beforeClose() {
      this.cancel()
    },
    // 调用教师接口获取相应信息通过教师姓名或ID
    teacherRemoteMethod(query) {
      if (query !== '') {
        this.loading = true
        let lang = this.$store.getters.language
        findTeacherList({ condition: query }).then(res => {
          this.loading = false;
          if (res.code == 200) {
            const list = res.data.list ? res.data.list : []
            this.options.teacherList = list.map(e => {
              return {
                value: e.code,
                facultyI18n: e.facultyI18n,
                label: lang === 'cn' ? e.name : e.nameEn,
                type: e.type
              }
            })
          }
        })
      } else {
        this.options.teacherList = []
      }
    },
    // 指定录入人二次确认
    confirmSettingEnterPerson() {
      this.dialogForm.selectTeacherName = ''
      this.options.teacherList = []
      this.settingEnterPerson = false
      this.$refs.teacherDialog.open()
      this.$nextTick(() => {
        this.$refs.dialogForm.clearValidate()
      })
    },
    // 取消
    cancel() {
      this.dialogVisible = false
      Object.keys(this.dialogForm).forEach(key => this.dialogForm[key] = '')
      this.$refs['dialogForm'].clearValidate()
    },
    // 确定
    confirm() {
      this.$refs['dialogForm'].validate(valid => {
        if (valid) {
          let teacherInfo = this.options.teacherList.find(item => {
            return item.value === this.dialogForm.selectTeacherName
          })
          let ids = this.multipleSelection.map(value => {
            return value.id
          })
          let params = {
            "code": teacherInfo.value,
            "ids": ids
          }
          scoreManagementApi.pointAuditPerson(params).then(res => {
            if (res.code === 200) {
              this.$message({
                type: 'success', 
                message: this.$t('scoreMangementBase.pointSuccessfully')
              })
              if (this.operateMode) {
                this.cancel()
                this.indexKey = 1
              } else {
                this.cancel()
                this.onSubmit()
              }
            }
          })
        } else {
          setTimeout(() => {
            let isError = document.getElementsByClassName("is-error");
            if (isError[0] && isError[0] && isError[0].querySelector('input')) {
              isError[0].querySelector('input').focus();
            }
          }, 1);
        }
      })
    }
  },
  watch: {
    auths: {
      handler(newVal) {
        if (newVal && Array.isArray(newVal) && newVal.length > 0) {
          newVal.some(item => {
            // 指定审核人
            if (item.authCode === 'scoreChangeAudit-designate-reviewer') {
              this.permitToPointAudit = true;
            }
            // 查看
            if (item.authCode === 'scoreChangeAudit-select') {
              this.permitToSelect = true;
            }
            // 审核
            if (item.authCode === 'scoreChangeAudit-audit') {
              this.permitToAudt = true;
            }
            // 一级审核人
            if (item.authCode === 'scoreChangeAudit-level-one-audit') {
              this.permitToLevelOneAudit = true;
            }
          })
        }
      },
      deep: true,
      immediate: true
    }
  }
}
</script>

<style lang="scss" scoped>
  .score-change-apply-container ::v-deep {
    .div-main {
      margin-bottom: 16px;
    }
  }
</style>